﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Agents.Admin
{
    public partial class ChooseProduct : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Vered - 14.08.2012 - Enable sorting with paging (bind manually)
            DataGridProjects.DataSource = SqlDataSource1;
            DataGridProjects.DataBind();

            // Save data to the view state to use after postback
            ViewState["NameSortDirection"] = "ASC";
            ViewState["sortExpression"] = "Name ASC";
        }

        //function deletes the chosen product from the database.
        protected void DataGridProjects_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            //retrieving the name of the product chosen by the administrator.
            string name = e.Item.Cells[1].Text;
            
            //creating a query object for accessing the database.
            Queries queries = new Queries();
            Product product = queries.GetProduct(name);

            //deleting the product chosen from the data bade.
            queries.DeleteProduct(name);

            // Refresh the grid
            DataGridProjects.DataBind();
        }

        //function redirects to the edit page of the product chosen by the administrator.
        protected void DataGridProjects_EditCommand1(object source, DataGridCommandEventArgs e)
        {
            //retrieving the name of the chosen product.
            int productId = Int32.Parse(e.Item.Cells[0].Text);

            //redirecting tho the products edit page.
            Response.Redirect("~/Admin/EditProduct.aspx?productId=" + productId);
        }

        //function redirects the agent back to his homepage when the "back" button is pressed.
        protected void backBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }

        //function handles the page indexing.
        protected void DataGridProjects_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            // Re-Bind the data
            string sortExpression = (string)ViewState["sortExpression"];
            Object dataSource = (sortExpression == null) ? SqlDataSource1.Select(DataSourceSelectArguments.Empty) :
                SqlDataSource1.Select(new DataSourceSelectArguments(sortExpression));
            DataGridProjects.DataSource = dataSource;

            // Updating the current page for the data grid to display.
            DataGridProjects.CurrentPageIndex = e.NewPageIndex;

            // Binding the data.
            DataGridProjects.DataBind();
        }

        /// <summary>
        /// Sort the data grid according to the clicked field
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void DataGridProjects_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            // Determine the direction for this sort
            string sortDirectionKey = e.SortExpression + "SortDirection";
            string sortExpression = e.SortExpression;
            string sortDirection = (string)ViewState[sortDirectionKey];

            if ((sortDirection != null) && (sortDirection.Equals("ASC")))
            {
                ViewState[sortDirectionKey] = "DESC";
            }
            else
            {
                ViewState[sortDirectionKey] = "ASC";
            }

            sortExpression += " " + ViewState[sortDirectionKey];

            // Save the sort expression (so we can use it for paging)
            ViewState["sortExpression"] = sortExpression;

            // Re-bind the data grid
            DataGridProjects.DataSource = SqlDataSource1.Select(new DataSourceSelectArguments(sortExpression));
            DataGridProjects.DataBind();
        }

        /// <summary>
        /// Occurs when the item is data bound, and checks whether this product
        /// can be deleted
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DataGridProjects_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) ||
                (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                // Get the product id of current product
                int productId = Int32.Parse(e.Item.Cells[0].Text);
                Queries queries = new Queries();

                // If there are stock orders with this product, don't allow deleted
                if (queries.GetProductNumberOfItemsInPendingStockOrders(productId) > 0)
                {
                    // Disable the link
                    LinkButton linkButton = ((LinkButton)e.Item.Cells[5].Controls[1]);
                    linkButton.Visible = false;
                    Label lblDelete = new Label();
                    lblDelete.Text = "מחק";
                    lblDelete.Attributes.CssStyle[HtmlTextWriterStyle.Color] = "gray";
                    lblDelete.Attributes.CssStyle[HtmlTextWriterStyle.Cursor] = "default";
                    e.Item.Cells[5].Controls.Add(lblDelete);

                    // Add the tooltip to explain why the link is disabled
                    e.Item.Cells[5].ToolTip = 
                        "לא ניתן למחוק את המוצר מכיוון שיש הזמנות מלאי ממתינות המכילות אותו";
                }
            }
        }

        /// <summary>
        /// Occurs when the user filters or unfilters the results by
        /// the agent's name, and updates results.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFilter_Click(object sender, EventArgs e)
        {
            // Filter
            if ((btnFilter.Text == "סנן") && (!String.IsNullOrEmpty(txtProductName.Text)))
            {
                SqlDataSource1.FilterExpression =
                    String.Format("Name LIKE '%{0}%'", txtProductName.Text);
                btnFilter.Text = "בטל סינון";
                DataGridProjects.DataBind();
            }
            // Unfilter
            else
            {
                SqlDataSource1.FilterExpression = null;
                btnFilter.Text = "סנן";
                DataGridProjects.DataBind();
            }
        }
    }
}